package com.gcb.controller.common;

import cn.hutool.core.collection.CollUtil;
import com.gcb.common.config.GcbConfig;
import com.gcb.common.constant.CacheConstants;
import com.gcb.common.constant.Constants;
import com.gcb.common.core.domain.AjaxResult;
import com.gcb.common.core.domain.dto.SysUserSearchDto;
import com.gcb.common.core.domain.vo.SysUserDetailVo;
import com.gcb.common.core.redis.RedisCache;
import com.gcb.common.enums.StatusEnum;
import com.gcb.common.enums.VerifyCodeCacheKeyEnum;
import com.gcb.common.exception.ServiceException;
import com.gcb.common.utils.StringUtils;
import com.gcb.common.utils.huawei.SmsUtils;
import com.gcb.common.utils.sign.Base64;
import com.gcb.common.utils.uuid.IdUtils;
import com.gcb.framework.service.ISysConfigService;
import com.gcb.framework.service.ISysUserService;
import com.gcb.service.ICommonService;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class VerifyCodeController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICommonService commonService;

    /**
     * 生成图片验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = GcbConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    /**
     * 验证码登录时校验手机号是否注册
     */
    @GetMapping("/phoneIsRegister")
    public AjaxResult phoneIsRegister(@RequestParam(name = "phone") String phone){
        if (!Pattern.compile("^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$").matcher(phone).matches()) {
            return AjaxResult.error("手机号格式错误");
        }
        //校验该手机号是否注册
        SysUserSearchDto sysUserSearchDto = new SysUserSearchDto();
        sysUserSearchDto.setPhonenumber(phone);
        List<SysUserDetailVo> sysUserDetailVos = userService.querySysUserByDtoCondi(sysUserSearchDto);
        AjaxResult responseAjax = null;
        if (sysUserDetailVos != null){
            //0 已注册，1 未注册，2 数据错误
            if (CollUtil.isEmpty(sysUserDetailVos)){
                throw new ServiceException("当前手机号未注册账号");
            }

            //该手机号已注册
            SysUserDetailVo sysUserDetailVoDB = sysUserDetailVos.get(0);
            if (StatusEnum.DELETED.getCode().equals(sysUserDetailVoDB.getDelFlag())) {
                throw new ServiceException("该用户已被删除");
            }
            else if (StatusEnum.DISABLE.getCode().equals(sysUserDetailVoDB.getStatus())) {
                throw new ServiceException("该用户已被停用");
            }

            if (sysUserDetailVos.size() > 1){
                throw new ServiceException("该用户手机号已被注册，且注册用户有多个，数据错误");
            }
        } else {
            throw new ServiceException("当前手机号未注册账号");
        }
        return AjaxResult.success();
    }
    /**
     * 后台管理系统发送短信验证码
     */
    @GetMapping("/sendSysVerifyCode")
    public AjaxResult sendSysVerifyCode(@RequestParam(name = "phone") String phone){
        commonService.sendVerifyCode(phone, VerifyCodeCacheKeyEnum.MANAGER);
        return AjaxResult.success();
    }
}
